import greenfoot.*;  
import java.util.ArrayList;
import java.util.Collections;

public class GameWorld extends World {
    private ArrayList<Block> blocks = new ArrayList<Block>();
    private int bombCount; // 保存地雷数量

    private Timer timer;
    private int width,height,bombs;
    public GameWorld(int width, int height, int bombs) {    
        super(width, height + 1, 25);    
        this.width=width;
        this.height=height;
        this.bombs=bombs;
        setBackground(new GreenfootImage(width, height + 1)); // 创建全白背景
        getBackground().setColor(Color.WHITE); // 设置背景颜色为白色
        getBackground().fill(); // 填充背景
        
        initializeBlocks(width, height, bombs);
        
        timer = new Timer(); // 创建计时器实例
        addObject(timer, width / 2, height + 30); // 将计时器放在右上角
        timer.start(); // 启动计时器
    }

    private void initializeBlocks(int width, int height, int bombs) {
        for (int i = 0; i < width; i++) {
            for (int j = 0; j < height; j++) {
                Block block = new Block();        
                blocks.add(block);                
                addObject(block, i, j);           
            }
        }
        Collections.shuffle(blocks);    
        for (int i = 0; i < bombs; i++) {      
            blocks.get(i).setBomb();      
        }
    }

    public void showAllBomb() {
        for (Block block : blocks) {
            if (block.getBomb()) {
                block.setImage("Bomb.png");
            }
        }
        Greenfoot.delay(10);
        Greenfoot.setWorld(new GameOverWorld(false,width,height,bombs));
    }

    public int getBombCount() {
        return bombCount; // 提供地雷数量的访问方法
    }

    public void act() {
        // 检查胜利条件：所有非地雷方块都已翻开
        boolean allNonBombsOpen = true;
        for (Block block : blocks) {
            if (!block.getBomb() && !block.isOpen()) {
                allNonBombsOpen = false;
                break;
            }
        }
        
        if (allNonBombsOpen) {
            Greenfoot.playSound("win.wav");
            Greenfoot.setWorld(new GameOverWorld(true,width,height,bombs)); // 胜利界面
        }
        
        // 检查失败条件：打开地雷
        for (Block block : blocks) {
            if (block.getBomb() && block.isOpen()) {
                Greenfoot.setWorld(new GameOverWorld(false,width,height,bombs)); // 失败界面
                break;
            }
        }
    }
}
